package com.example.trafficsystem.service;

import com.example.trafficsystem.entity.*;
import com.example.trafficsystem.repository.ExamAnswerRe;
import com.example.trafficsystem.repository.ExamQuestionRe;
import com.example.trafficsystem.repository.ExamRe;
import com.example.trafficsystem.repository.ExamRecordRe;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.web.server.ResponseStatusException;

import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;

@Service
public class ExamService {

    @Autowired
    private ExamRe examRepository;
    @Autowired
    private ExamQuestionRe examQuestionRepository;
    @Autowired
    private ExamRecordRe examRecordRepository;
    @Autowired
    private ExamAnswerRe examAnswerRepository;

    // 获取培训计划的考试
    public Exam getExamForTrainingPlan(Long trainingPlanId) {
        return examRepository.findByTrainingPlanId(trainingPlanId);
    }

    // 获取考试题目
    public List<ExamQuestion> getExamQuestions(Long examId) {
        Optional<Exam> byId = examRepository.findById(examId);
        return byId.get().getQuestions();
    }

    // 学员开始考试
    public ExamRecord startExam(Long studentId, Long examId) {
        Exam exam = examRepository.findById(examId).orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "Exam not found"));
        ExamRecord record = new ExamRecord();
        record.setExam(exam);
        record.setStudent(new Student()); // 获取学员
        record.getStudent().setId(studentId);
        record.setStartTime(LocalDateTime.now());
        record.setIsSubmitted(false);
        return examRecordRepository.save(record);
    }

    // 学员提交考试
    public ExamRecord submitExam(Long examRecordId, List<Object> answers) {
        ExamRecord record = examRecordRepository.findById(examRecordId).orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "Exam record not found"));

        if (record.getIsSubmitted()) {
            throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "考试已提交");
        }

        // 评分逻辑
        int score = 0;
        List<ExamQuestion> questions = getExamQuestions(record.getExam().getId());

        for (int i = 0; i < questions.size(); i++) {
            ExamAnswer examAnswer = new ExamAnswer();
            examAnswer.setExamRecord(record);
            examAnswer.setExamQuestion(questions.get(i));
            examAnswer.setAnswer(answers.get(i).toString());

            // 获取正确答案
            String correctAnswer = questions.get(i).getCorrectAnswer();
            Object studentAnswer = answers.get(i);
            String questionType = questions.get(i).getQuestionType();

            // 判断答案是否正确
            if ("单选".equals(questionType)) {
                // 单选题：判断答案是否完全一致
                if (isAnswerCorrect(studentAnswer.toString(), correctAnswer)) {
                    examAnswer.setIsCorrect(true);
                    score += questions.get(i).getScore(); // 累加分数
                } else {
                    examAnswer.setIsCorrect(false);
                }
            } else if ("多选".equals(questionType)) {
                // 多选题：判断选项是否完全一致（顺序无关）
                if (isMultipleChoiceAnswerCorrect(studentAnswer.toString(), correctAnswer)) {
                    examAnswer.setIsCorrect(true);
                    score += questions.get(i).getScore(); // 累加分数
                } else {
                    examAnswer.setIsCorrect(false);
                }
            }

            examAnswerRepository.save(examAnswer); // 保存答案记录
        }

        // 设置分数和评价
        record.setScore(score);
        record.setEvaluation(generateEvaluation(score));
        record.setSubmitTime(LocalDateTime.now());
        record.setIsSubmitted(true);

        return examRecordRepository.save(record);
    }


    // 判断单选题答案是否正确
    private boolean isAnswerCorrect(String studentAnswer, String correctAnswer) {
        return studentAnswer.equalsIgnoreCase(correctAnswer);
    }

    // 判断多选题答案是否正确（答案顺序不影响）
    // 判断多选题答案是否正确（答案顺序不影响）
    private boolean isMultipleChoiceAnswerCorrect(String studentAnswer, String correctAnswer) {
        // 将答案按字母排序后比较
        String[] studentAnswers = studentAnswer.split(",");
        String[] correctAnswers = correctAnswer.split(",");

        Arrays.sort(studentAnswers);
        Arrays.sort(correctAnswers);

        // 判断学员的答案与正确答案是否完全一致
        return Arrays.equals(studentAnswers, correctAnswers);
    }

    // 根据分数生成评价
    private String generateEvaluation(int score) {
        if (score >= 90) {
            return "优秀";
        } else if (score >= 75) {
            return "良好";
        } else if (score >= 60) {
            return "及格";
        } else {
            return "不及格";
        }
    }

    // 获取考试记录
    public ExamRecord getExamRecord(Long examRecordId) {
        return examRecordRepository.findById(examRecordId).orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "Exam record not found"));
    }
}
